<template>
    <div style="height:100%">

        <el-alert
                title="题目添加表单"
                type="success">
        </el-alert>
        <br>
        <div class="cateform" style="width:50%">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

                <el-form-item label="标题" prop="question">
                    <el-input v-model="ruleForm.title"></el-input>
                </el-form-item>
                <el-form-item label="分类" prop="question">
                    <el-select v-model="ruleForm.type" placeholder="请选择">
                        <el-option
                                label="科目一"
                                value="1">
                        </el-option>
                        <el-option
                                label="科目三"
                                value="1">
                        </el-option>
                        <el-option
                                label="科目四"
                                value="4">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="描述" style="height:440px;width: 1010px;">
                    <!-- 图片上传组件辅助-->
                    <el-upload
                            class="avatar-uploader"
                            :action="serverUrl"
                            name="img"
                            :headers="header"
                            :show-file-list="false"
                            :on-success="uploadSuccess"
                            :on-error="uploadError"
                            :before-upload="beforeUpload">
                    </el-upload>
                    <!-- bidirectional data binding（双向数据绑定） -->
                    <el-row v-loading="quillUpdateImg">
                        <quill-editor  v-model="ruleForm.content"
                                       ref="myQuillEditor"
                                       :options="editorOption"
                                       @change="onEditorChange($event)"
                                       @ready="onEditorReady($event)">
                        </quill-editor>
                    </el-row>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                    <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>
            </el-form>

        </div>
    </div>
</template>

<script>
    // require styles
    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.snow.css'
    import 'quill/dist/quill.bubble.css'

    import { quillEditor } from 'vue-quill-editor'

    // 工具栏配置
    const toolbarOptions = [
        ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
        ['blockquote', 'code-block'],

        [{'header': 1}, {'header': 2}],               // custom button values
        [{'list': 'ordered'}, {'list': 'bullet'}],
        [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
        [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
        [{'direction': 'rtl'}],                         // text direction

        [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
        [{'header': [1, 2, 3, 4, 5, 6, false]}],

        [{'color': []}, {'background': []}],          // dropdown with defaults from theme
        [{'font': []}],
        [{'align': []}],
        ['link', 'image', 'video'],
        ['clean']                                         // remove formatting button
    ]
    export default {
        components: {
            quillEditor
        },
        mounted(){
            axios.post('getcate').then(rew=>{
                this.catelists = rew.data
            })
            axios.post('getchapters').then(rew=>{
                this.chapters = rew.data
            })
        },
        data() {
            return {
                quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
                serverUrl: '/api/ImageUpload',  // 这里写你要上传的图片服务器地址
                header: {token: sessionStorage.token},  // 有的图片服务器要求请求头需要有token之类的参数，写在这里
                detailContent: '', // 富文本内容
                editorOption: {
                    placeholder: '',
                    theme: 'snow',  // or 'bubble'
                    modules: {
                        toolbar: {
                            container: toolbarOptions,  // 工具栏
                            handlers: {
                                'image': function (value) {
                                    if (value) {
                                        // 触发input框选择图片文件
                                        document.querySelector('.avatar-uploader input').click()
                                    } else {
                                        this.quill.format('image', false);
                                    }
                                }
                            }
                        }
                    }
                },
                fileList2:[],
                ruleForm: {
                    title: '',
                    content: '<h2>请输入内容</h2>',
                    type:''
                },
                catelists:[],
                chapters:[],
                fileList: {
                    name: '',
                    url: ''
                },
                rules: {


                }
            };
        },
        methods: {
            // 上传图片前
            beforeUpload(res, file) {
                // 显示loading动画
                this.quillUpdateImg = true
            },
            // 上传图片成功
            uploadSuccess(res, file) {
                // res为图片服务器返回的数据
                // 获取富文本组件实例
                let quill = this.$refs.myQuillEditor.quill
                // 如果上传成功
                if (res.code === '200' && res.url !== null) {
                    // 获取光标所在位置
                    let length = quill.getSelection().index;
                    // 插入图片  res.info为服务器返回的图片地址
                    quill.insertEmbed(length, 'image', res.url)
                    // 调整光标到最后
                    quill.setSelection(length + 1)
                } else {
                    this.$message.error('图片插入失败')
                }
                // loading动画消失
                this.quillUpdateImg = false
            },

            // 富文本图片上传失败
            uploadError() {
                // loading动画消失
                this.quillUpdateImg = false
                this.$message.error('图片插入失败')
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.post('/api/ProblemAdd',this.ruleForm).then(rew=>{
                            if(rew.data==200){
                                this.open2()
                            }
                            if(rew.data==400){
                                this.open4()
                            }
                            if(rew.data==300){
                                this.open3()
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            change(val){
                let data = {
                    id:val,
                }

                axios.post('/api/GetSubTwoLevel2',data).then(rew=>{
                    this.ruleForm.level2=''
                    this.catelists2 = rew.data.sub_twos
                    this.isShow = true
                })
            },
            handleSuccess(url){
                this.ruleForm.url = url.id
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            open2() {
                this.$notify({
                    title: '添加成功',
                    message: '点击关闭',
                    type: 'success'
                });
            },
            open4() {
                this.$notify({
                    title: '该视频文件已存在，请尝试更换文件名',
                    message: '点击关闭',
                    type: 'error'
                });
            },
            open3() {
                this.$notify({
                    title: '标题已存在',
                    message: '点击关闭',
                    type: 'error'
                });
            },
            onEditorBlur(quill) {
                console.log('editor blur!', quill)
            },
            onEditorFocus(quill) {
                console.log('editor focus!', quill)
            },
            onEditorReady(quill) {
                console.log('editor ready!', quill)
            },
            onEditorChange({ quill, html, text }) {
                console.log('editor change!', quill, html, text)
                this.content = html
            }
        },
        computed: {
            editor() {
                return this.$refs.myQuillEditor.quill
            }
        }
    }
</script>

<style>
    .quill-editor {
        height: 300px;

    .ql-container {
        height: 350px;
    }
    }
</style>